"""
通道突破策略(backtrader实现)
策略逻辑：
1. 当价格突破N日最高点时买入
2. 当价格跌破N日最低点时卖出
"""

import backtrader as bt

class ChannelBreakoutStrategy(bt.Strategy):
    params = (
        ('period', 20),  # 通道计算周期
    )

    def __init__(self):
        # 计算通道上下轨
        self.high_channel = bt.indicators.Highest(self.data.high, period=self.p.period)
        self.low_channel = bt.indicators.Lowest(self.data.low, period=self.p.period)

    def next(self):
        if not self.position:  # 没有持仓
            if self.data.close[0] > self.high_channel[0]:  # 突破上轨
                self.buy()  # 买入
        elif self.data.close[0] < self.low_channel[0]:  # 跌破下轨
            self.close()  # 卖出

if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(ChannelBreakoutStrategy)
    # 这里添加数据和其他配置
    cerebro.run()